/**
 * @Title: DailyReportActivity.java
 * @Package: com.jason.fingerprint.ui
 * @Descripton: TODO
 * @Author: Jason.Zhang zhangyujn1989ok@gmail.com
 * @Date: 2014年11月9日 下午4:55:51
 * @Version: V1.0
 */
package com.jason.fingerprint.ui;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.jason.fingerprint.AppContext;
import com.jason.fingerprint.R;
import com.jason.fingerprint.adapter.DailyReportAdapter;
import com.jason.fingerprint.beans.DailyReportBean;
import com.jason.fingerprint.beans.RecordBean;
import com.jason.fingerprint.beans.ui.FingerPrintBean;
import com.jason.fingerprint.beans.ui.ImageOrAudioBean;
import com.jason.fingerprint.common.DataHelper;
import com.jason.fingerprint.common.DialogHelper;
import com.jason.fingerprint.common.UIHelper;
import com.jason.fingerprint.logic.DailyReportSyncLogic;
import com.jason.fingerprint.logic.MatchFingerprintSyncLogic;
import com.jason.fingerprint.utils.DataUtils;
import com.jason.fingerprint.widget.LoadingDialog;

import org.kymjs.aframe.database.DbModel;
import org.kymjs.aframe.database.KJDB;
import org.kymjs.aframe.ui.BindView;
import org.kymjs.aframe.ui.KJActivityManager;
import org.kymjs.aframe.ui.activity.BaseActivity;
import org.kymjs.aframe.utils.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: DailyReportActivity
 * @Description: 日常报到
 * @Author: Jason.Zhang zhangyujn1989ok@gmail.com
 * @Date: 2014年11月9日 下午4:55:51
 */
@SuppressLint({ "NewApi", "HandlerLeak" })
public class DailyReportActivity extends BaseActivity implements
		OnItemClickListener {

	private static final String TAG = "DailyReportActivity";

	public static final int CHOOSE_RECORD_REQUEST_OK = 1003;
	private static final long FINGER_AGAIN_TIME = 1500L;

	@BindView(id = R.id.header_back, click = true)
	private Button mBackButton;
	@BindView(id = R.id.header_title)
	private TextView mTitleTextView;
	@BindView(id = R.id.daily_report_button_begin, click = true)
	private Button mBeginButton;
	@BindView(id = R.id.daily_report_button_end, click = true)
	private Button mEndButton;
	@BindView(id = R.id.daily_report_button_takephoto, click = true)
	private Button mTakePhotoButton;
	@BindView(id = R.id.daily_report_button_upload, click = true)
	private Button mUploadButton;
	@BindView(id = R.id.daily_listview)
	private ListView mListView;

	private AppContext mAppContext;

	private MatchFingerprintSyncLogic mLogic;
	private Context mContext;
	private KJDB mKjdb;
	private DailyReportAdapter mDailyReportAdapter;
	private List<DailyReportBean> mDailyReportBeans;

	private int mChooseImageCount = 1;
	private List<String> mCacheCheckImages = new ArrayList<String>();
	private int mState = 1;// 1 开始签到，2结束签到
	private FingerPrintBean mFingerPrintBean;
	private DailyReportBean mDailyReportBean;
	private int mMaxId;
	private String mRymcId;
	private LoadingDialog mProgressDialog;

	/***
	 * 统计上传成功、失败的条数
	 * mNeedStartUploadCount：开始需要上传的条数
	 * mNeedEndUploadCount：结束需要上传的条数（失败的条数）
	 * 成功的条数=mNeedStartUploadCount-mNeedEndUploadCount
	 */
	private int mNeedStartUploadCount = 0;
	private int mNeedEndUploadCount = 0;
	//选取用户
	private RecordBean mRecordBean;

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.kymjs.aframe.ui.activity.I_KJActivity#setRootView()
	 */
	@Override
	public void setRootView() {
		setContentView(R.layout.activity_daily_report);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.kymjs.aframe.ui.activity.KJFrameActivity#initWidget()
	 */
	@Override
	protected void initWidget() {
		// TODO Auto-generated method stub
		super.initWidget();
		mAppContext = (AppContext) getApplication();
		mListView.setOnItemClickListener(this);
		mProgressDialog = new LoadingDialog(this);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.kymjs.aframe.ui.activity.KJFrameActivity#initData()
	 */
	@Override
	protected void initData() {
		super.initData();
		mTitleTextView.setText("日常报到");
		mContext = this;
		mAppContext = (AppContext) getApplication();
		mKjdb = mAppContext.getKjdb();
		// 获取当前的所有所有签到信息
		loadReportBeans();
		mDailyReportAdapter = new DailyReportAdapter(mContext);
		mDailyReportAdapter.addAll(mDailyReportBeans);
		mListView.setAdapter(mDailyReportAdapter);
		mDailyReportAdapter.notifyDataSetChanged();
		initFinger();
	}
	
	// 初始化指纹信息
	private void initFinger() {
		mLogic = new MatchFingerprintSyncLogic(this);
		mLogic.setHandle(mDailyReportFingerpringHandler);
		mLogic.isManager(false);
	}

	private void loadReportBeans() {
		try {
			mDailyReportBeans = mKjdb.findAllByWhere(DailyReportBean.class,
					getQueryWhere(), "updateTime");
		} catch (Exception e) {
		}
	}

	// 当天，记录没有上传
	private String getQueryWhere() {
		long startTime = DataUtils.getCurrentDayBeginDate().getTime();
		long endTime = DataUtils.getCurrentDayEndDate().getTime();
//		String where = "startTime >= " + startTime + " and startTime <= "
//				+ endTime + " or state = 1";
		String where = " state = 1 ";
		Log.i(TAG, "--------->getQueryWhere where:" + where);
		return "";
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.kymjs.aframe.ui.activity.KJFrameActivity#widgetClick(android.view
	 * .View)
	 */
	@Override
	public void widgetClick(View v) {
		super.widgetClick(v);
		switch (v.getId()) {
		case R.id.header_back:
			KJActivityManager.create().finishActivity(this);
			break;
		case R.id.daily_report_button_begin:
			// TODO 开始签到（此处模拟数据）
			mState = 1;
			fingerPrintMatch();
			break;
		case R.id.daily_report_button_end:
			// TODO 结束签到
			mState = 2;
			fingerPrintMatch();
			break;
		case R.id.daily_report_button_takephoto:
			// TODO 拍照（待定，是否预留拍照入口）
			break;
		case R.id.daily_report_button_upload:
			// 上传记录
			mProgressDialog.setIsOut(false);
			mProgressDialog.setMessage("请稍等，正在上传记录...");
			mProgressDialog.show();
			//统计需要上传的条数
			mNeedStartUploadCount = 0;
			List<DailyReportBean> beans = mKjdb.findAllByWhere(DailyReportBean.class,
					" state = 1 ", "updateTime");
			if (beans != null && !beans.isEmpty()){
				mNeedStartUploadCount = beans.size();
			}
			DailyReportSyncLogic logic = new DailyReportSyncLogic(
					mAppContext, mUploadHandler, true);
			logic.execute();
			break;

		default:
			break;
		}
	}
	
	private Handler mUploadHandler = new Handler(){
		
		@Override
		public void handleMessage(Message msg) {
			if (mProgressDialog != null ) {
				mProgressDialog.dismiss();
			}
			mNeedEndUploadCount = 0;
			List<DailyReportBean> beans = mKjdb.findAllByWhere(DailyReportBean.class,
					" state = 1 ", "updateTime");
			if (beans != null && !beans.isEmpty()){
				mNeedEndUploadCount = beans.size();
			}
			switch (msg.what) {
			case UIHelper.FILE_UPLOAD_SUCCESS:
				//Toast.makeText(mContext, "上传完成", Toast.LENGTH_SHORT).show();
				Toast.makeText(mContext, "总上传" + mNeedStartUploadCount + "条，成功" +  (mNeedStartUploadCount - mNeedEndUploadCount) + "条，失败" + mNeedEndUploadCount + "条", Toast.LENGTH_SHORT).show();
				loadReportBeans();
				mDailyReportAdapter.addAll(mDailyReportBeans);
				break;
			case UIHelper.FILE_UPLOAD_FAIL:
				Toast.makeText(mContext, "总上传" + mNeedStartUploadCount + "条，成功" +  (mNeedStartUploadCount - mNeedEndUploadCount) + "条，失败" + mNeedEndUploadCount + "条", Toast.LENGTH_SHORT).show();
				//Toast.makeText(mContext, "上传失败，请重试", Toast.LENGTH_SHORT).show();
				break;
			case UIHelper.HTTP_CODE_TIMEOUT:
				Toast.makeText(mContext, "网络连接超时", Toast.LENGTH_SHORT).show();
				break;

			default:
				break;
			}
		};
	};

	private Handler mDailyReportFingerpringHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			Message message = new Message();
			switch (msg.what) {
			case UIHelper.FINGERPRINT_UPCHAR_SUCCESS:
				break;
			case UIHelper.FINGERPRINT_UPCHAR_FAIL:// char--返回失败
			case UIHelper.FINGERPRINT_REGMODE_FAIL:// char--模板合成失败
			case UIHelper.FINGERPRINT_GENCHAR_FAIL:// char--生成特征值失败
			case UIHelper.FINGERPRINT_DELETECHAR_FAIL:// char--模板下载失败
			case UIHelper.FINGERPRINT_UPIMAGE_FAIL:// image--生成失败
			case UIHelper.FINGERPRINT_SEARCH_FAIL:
				message.what = 101;
				mMatchHandler.handleMessage(message);
				break;
			case UIHelper.FINGERPRINT_SEARCH_SUCCESS:
				// 匹配成功
				int pageId = msg.arg1;
				message.what = 100;
				message.arg1 = pageId;
				mMatchHandler.handleMessage(message);
				break;
			case UIHelper.FINGERPRINT_AGAIN:// 再次按手指
				mProgressDialog.setIsOut(true);
				mProgressDialog.setMessage("请再次按指纹...");
				mProgressDialog.show();
				new Handler().postDelayed(mFingerAgainRunnable, FINGER_AGAIN_TIME);
			case UIHelper.FINGERPRINT_ONMATCH_SUCCESS:// image--图片合成成功

				break;

			default:
				break;
			}
		};

	};

	private Runnable mFingerAgainRunnable = new Runnable() {

		@Override
		public void run() {
			if (mLogic != null){
				mLogic.executeAgain();
			}
		}
	};

	// 指纹验证结果回调
	private Handler mMatchHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			if (mProgressDialog != null) {
				mProgressDialog.dismiss();
			}
			if (mLogic != null) {
				mLogic.destory();
			}
			switch (msg.what) {
			case 100:
				// 匹配成功
				int pageId = msg.arg1;
				saveData(pageId);
				break;
			case 101:
				//TODO 匹配失败 ，弹出图片签到的Dialog
//				Toast.makeText(mContext, "没有找到匹配的指纹", Toast.LENGTH_SHORT)
//						.show();
				takePhotoSign();
				break;

			default:
				break;
			}
		};
	};

	//进行拍照签到，选取矫正人员
	private void takePhotoSign() {
		// 拍照
		mRecordBean = null;
		new AlertDialog.Builder(this)
				.setTitle("拍照签到")
				.setMessage("没有找到匹配的指纹,是否进行拍照签到？")
				.setCancelable(true)
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						chooseRecordInfo();
					}

				})
				.setNegativeButton("取消", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}

				}).create().show();
	}

	// 选取矫正人员
	private void chooseRecordInfo() {
		Intent intent = new Intent(DailyReportActivity.this, RecordActivity.class);
		intent.putExtra(RecordActivity.RECORD_STATE,
				RecordActivity.CHOOSE_RECORD_STATE);
		startActivityForResult(intent, CHOOSE_RECORD_REQUEST_OK);
	}

	// 指纹结果处理
	private void saveData(final int pageId) {
		Log.i(TAG, "-----> saveData--- pageId:" + pageId);
		List<FingerPrintBean> beans = mKjdb.findAllByWhere(
				FingerPrintBean.class, " id = " + pageId + " and type = 1");//矫正人员
		FingerPrintBean bean = mKjdb.findById(pageId, FingerPrintBean.class);
		if (bean != null && bean.getType() == 1) {
			mFingerPrintBean = bean;
			Log.i(TAG, "-----> saveData--- " + mFingerPrintBean);
			if (mFingerPrintBean != null) {
				String userId = mFingerPrintBean.getUserId();// 获取当前矫正人员的id
				if (!StringUtils.isEmpty(userId)) {
					Log.i(TAG, "-----> saveData--- userId:" + userId);
					beginDailyReport();
					takePhoto(DialogHelper.CHOOSE_PHOTO_REQUEST_OK);
//					boolean flag = isSuccessDailyReport(userId, mState);
//					if (!flag) {
//						if (mState == 1) {
//							beginDailyReport();
//							takePhoto();
//						}
//					}else {
//						if (mState == 2) {
//							//修改信息
//							endDailyReport(getUpdateDailyReportBean(userId));
//						}
//					}
					return;
				}
			}
		}
		Toast.makeText(mContext, "没有找到匹配的指纹", Toast.LENGTH_SHORT).show();
	}

	// 开启指纹登录
	private synchronized void fingerPrintMatch() {
		if (mState == 1) {
			mProgressDialog.setMessage("正在开始签到...");
		}else if (mState == 2) {
			mProgressDialog.setMessage("正在结束签到...");
		}else {
			mProgressDialog.setMessage("正在签到...");
		}
		mProgressDialog.show();
		mLogic.execute();
		mProgressDialog.setMatchLogic(mLogic);
	}

	private void takePhoto(final int requestId) {
		// 拍照
		new AlertDialog.Builder(this)
				.setTitle("拍照")
				.setMessage("是否进行拍照？")
				.setCancelable(true)
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						Intent takePicture = new Intent(
								DailyReportActivity.this,
								ChoosePhotoActivity.class);
						takePicture.putExtra(
								ChoosePhotoActivity.CHOOSE_PHOTO_COUNT,
								mChooseImageCount);
						startActivityForResult(takePicture,requestId);
					}

				})
				.setNegativeButton("取消", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}

				}).create().show();
	}

	private void beginDailyReport() {
		if (mFingerPrintBean != null) {
			mDailyReportBean = new DailyReportBean();
			mDailyReportBean.setRymcId(mFingerPrintBean.getUserId());
			mDailyReportBean.setRymcName(mFingerPrintBean.getUserName());
			mDailyReportBean.setStartTime(System.currentTimeMillis());
			mDailyReportBean.setUpdateTime(0l);
			mDailyReportBean.setUpdateTime(System.currentTimeMillis());
			mDailyReportBean.setState(1);
			mDailyReportBean.setRegistrationType(0);
			mKjdb.save(mDailyReportBean);
			
			// 获取当前保存的ID
			DbModel dbModel = mKjdb
					.findDbModelBySQL("select max(id) as id from table_dailyReport order by id desc");
			mMaxId = dbModel.getInt("id");
			mDailyReportBean.setId(mMaxId);
			mDailyReportAdapter.addOne(mDailyReportBean);
			Toast.makeText(this, "签到成功", Toast.LENGTH_SHORT).show();
		} else {
			Toast.makeText(this, "签到失败", Toast.LENGTH_SHORT).show();
		}
	}

	private void saveDailyReport(RecordBean bean){
		mDailyReportBean = new DailyReportBean();
		mDailyReportBean.setRymcId(bean.getElectronicsId());
		mDailyReportBean.setRymcName(bean.getName());
		mDailyReportBean.setStartTime(System.currentTimeMillis());
		mDailyReportBean.setUpdateTime(0l);
		mDailyReportBean.setUpdateTime(System.currentTimeMillis());
		mDailyReportBean.setState(1);
		mDailyReportBean.setRegistrationType(1);
		mKjdb.save(mDailyReportBean);

		// 获取当前保存的ID
		DbModel dbModel = mKjdb
				.findDbModelBySQL("select max(id) as id from table_dailyReport order by id desc");
		mMaxId = dbModel.getInt("id");
		mDailyReportBean.setId(mMaxId);
		mDailyReportAdapter.addOne(mDailyReportBean);
		Toast.makeText(this, "签到成功", Toast.LENGTH_SHORT).show();
	}
	
	//保存结束签到信息
	private void endDailyReport(DailyReportBean bean){
		if (bean != null) {
			bean.setEndTime(System.currentTimeMillis());
			bean.setUpdateTime(System.currentTimeMillis());
			mKjdb.update(bean);
			loadReportBeans();
//			Collections.sort(mDailyReportBeans, new DailyReportAdapter.MyComparator());
			mDailyReportAdapter.addAll(mDailyReportBeans);
			mDailyReportAdapter.notifyDataSetChanged();
//			mDailyReportAdapter.updateOne(bean);
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		Log.i(TAG,"onActivityResult requestCode:" + requestCode + ",resultCode:" + resultCode);
		if (requestCode == DialogHelper.CHOOSE_PHOTO_REQUEST_OK && resultCode == 1001) {
			if (data != null) {
				mCacheCheckImages = data
						.getStringArrayListExtra("mCacheCheckImages");
				// 保存图片到数据库
				if (mCacheCheckImages != null && !mCacheCheckImages.isEmpty()) {
					String path = mCacheCheckImages.get(0);
					savePhoto(path);
				}
			}
		}
		if (requestCode == DialogHelper.CHOOSE_PHOTO_RECORD_REQUEST_OK && resultCode == 1001) {
			if (data != null) {
				mCacheCheckImages = data
						.getStringArrayListExtra("mCacheCheckImages");
				if (mRecordBean != null){
					// 保存图片到数据库
					if (mCacheCheckImages != null && !mCacheCheckImages.isEmpty()) {
						String path = mCacheCheckImages.get(0);
						saveDailyReport(mRecordBean);
						savePhoto(path);
						mRecordBean = null;
					}
				}
			}
		}

		if (requestCode == CHOOSE_RECORD_REQUEST_OK && resultCode == RESULT_OK) {
			if (data != null) {
				mRecordBean = (RecordBean) data
						.getSerializableExtra("RecordBean");
				if (mRecordBean != null
						&& !StringUtils.isEmpty(mRecordBean.getElectronicsId())) {
					//TODO 打开拍照信息
					takePhoto(DialogHelper.CHOOSE_PHOTO_RECORD_REQUEST_OK);
				} else {
					Toast.makeText(mContext, "选择失败，请重新选择矫正人员信息",
							Toast.LENGTH_SHORT).show();
				}
			}
		}
	}

	// 把选取的图片保存到数据库
	private void savePhoto(String photoPath) {
		if (!StringUtils.isEmpty(photoPath) && mDailyReportBean != null) {
			ImageOrAudioBean bean = DataHelper.getImageOrAudioBeanInfoByPath(
					this, photoPath, 1);
			bean.setServiceId(1);
			bean.setParentId(String.valueOf(mMaxId));
			bean.setCreateDate(String.valueOf(mDailyReportBean.getStartTime()));
			Log.i(TAG, "---> savePhoto " + bean);
			mKjdb.save(bean);
		} else {
			Toast.makeText(this, "选取图片失败", Toast.LENGTH_SHORT).show();
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * android.widget.AdapterView.OnItemClickListener#onItemClick(android.widget
	 * .AdapterView, android.view.View, int, long)
	 */
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		DailyReportBean bean = (DailyReportBean) parent
				.getItemAtPosition(position);
		Intent intent = new Intent(DailyReportActivity.this,
				DailyReportDetailActivity.class);
		intent.putExtra("DailyReportBean", bean);
		startActivity(intent);
	}

	// 判断该用户是否已经开始签到了
	public boolean isSuccessDailyReport(String rymcId, int state) {
		if (StringUtils.isEmpty(rymcId)) {
			return false;
		}
		boolean flag = false;
		// 查看所有未完成的报到中是否存在，判断标准时结束时间是否为ol,假如存在则提示已经存在，结束签到，如果不存在开始签到
		String where = "";
		if (state == 1) {
			// 是否开始签到的查询条件
//			where = getQueryWhere() + " and rymcId = '" + rymcId + "'";
			where = " endTime = 0 and state = 1 and rymcId = '" + rymcId + "'";
		} else if (state == 2) {
			// 是否结束的查询条件
			where = " endTime = 0 and state = 1 and rymcId = '" + rymcId + "'";
		}
		List<DailyReportBean> beans = new ArrayList<DailyReportBean>();
		try {
			beans = mKjdb.findAllByWhere(DailyReportBean.class, where,
					"updateTime");

		} catch (Exception e) {
			return false;
		}
		if (beans != null && !beans.isEmpty()) {
			int size = beans.size();
			for (int i = 0; i < size; i++) {
				DailyReportBean bean = beans.get(i);
				if (bean != null) {
					String userId = bean.getRymcId();
					if (rymcId.equals(userId)) {
						flag = true;
						break;
					}
				}
			}
		}
		if (state == 1) {
			if (flag) {
				Toast.makeText(mContext, "请检查今天是否已经签到完毕或者未结束签到",
						Toast.LENGTH_SHORT).show();
			}
		}else if(state == 2){
			if (flag) {
//				Toast.makeText(mContext, "结束签到成功", Toast.LENGTH_SHORT).show();
			}else {
				Toast.makeText(mContext, "请预先开始签到", Toast.LENGTH_SHORT).show();
			}
		}
		return flag;
	}

	//获取要结束签到的报到信息
	private DailyReportBean getUpdateDailyReportBean(String rymcId){
		if (StringUtils.isEmpty(rymcId)) {
			return null;
		}
		List<DailyReportBean> beans = new ArrayList<DailyReportBean>();
		try {
			beans = mKjdb.findAllByWhere(DailyReportBean.class, "rymcId = '" + rymcId + "' and endTime = 0");
		} catch (Exception e) {
			return null;
		}
		if (beans != null && !beans.isEmpty()) {
			return beans.get(0);
		}
		return null;
	}
	
	/* (non-Javadoc)
	 * @see org.kymjs.aframe.ui.activity.BaseActivity#onStop()
	 */
	@Override
	protected void onStop() {
		if (mLogic != null) {
			mLogic.destory();
		}
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (mProgressDialog != null) {
			mProgressDialog.dismiss();
		}
	}
}
